package com.teacher.game.model;

import android.graphics.Color;
import android.graphics.Rect;
import com.teacher.ellio.Assets;
import com.teacher.game.framework.util.Painter;
import com.teacher.game.framework.util.RandomNumberGenerator;

/**
 * 组合障碍物 - 需要复合操作的复杂障碍物
 * 例如：需要先跳跃后下蹲，或者连续动作的障碍物
 */
public class ComboBlock extends AbstractObstacle {
    
    private Rect collisionRect = new Rect();
    
    // 组合类型
    public enum ComboType {
        JUMP_THEN_DUCK,     // 跳跃后下蹲
        DUCK_THEN_JUMP,     // 下蹲后跳跃  
        DOUBLE_JUMP,        // 需要二段跳
        TIMING_CRITICAL,    // 时机关键型
        WAVE_PATTERN        // 波浪模式
    }
    
    private ComboType comboType;
    
    // 组合障碍物的多个部分
    private ObstaclePart[] parts;
    private float partSpacing;          // 部分之间的间距
    private float comboTimer = 0;       // 组合计时器
    
    /**
     * 障碍物部分类
     */
    private static class ObstaclePart {
        float relativeX;    // 相对X坐标
        float relativeY;    // 相对Y坐标
        int width, height;
        boolean requiresJump;
        boolean requiresDuck;
        float activationDelay;  // 激活延迟
        boolean isActive = true;
        
        ObstaclePart(float relativeX, float relativeY, int width, int height, 
                    boolean requiresJump, boolean requiresDuck, float activationDelay) {
            this.relativeX = relativeX;
            this.relativeY = relativeY;
            this.width = width;
            this.height = height;
            this.requiresJump = requiresJump;
            this.requiresDuck = requiresDuck;
            this.activationDelay = activationDelay;
        }
        
        Rect getCollisionRect(float baseX, float baseY) {
            return new Rect(
                (int)(baseX + relativeX),
                (int)(baseY + relativeY),
                (int)(baseX + relativeX + width),
                (int)(baseY + relativeY + height)
            );
        }
    }
    
    /**
     * 构造函数
     */
    public ComboBlock(float x, float y, int width, int height) {
        super(x, y, width, height, ObstacleType.COMBO);
        
        // 随机选择组合类型
        ComboType[] types = ComboType.values();
        this.comboType = types[RandomNumberGenerator.getRandInt(types.length)];
        
        // 根据组合类型初始化部分
        initializeCombo();
    }
    
    /**
     * 初始化组合障碍物
     */
    private void initializeCombo() {
        switch (comboType) {
            case JUMP_THEN_DUCK:
                initJumpThenDuck();
                break;
                
            case DUCK_THEN_JUMP:
                initDuckThenJump();
                break;
                
            case DOUBLE_JUMP:
                initDoubleJump();
                break;
                
            case TIMING_CRITICAL:
                initTimingCritical();
                break;
                
            case WAVE_PATTERN:
                initWavePattern();
                break;
        }
    }
    
    /**
     * 初始化跳跃后下蹲模式
     */
    private void initJumpThenDuck() {
        partSpacing = 80;
        parts = new ObstaclePart[] {
            new ObstaclePart(0, -30, 20, 50, true, false, 0),      // 高障碍物
            new ObstaclePart(partSpacing, 30, 20, 30, false, true, 0.5f)  // 低障碍物
        };
    }
    
    /**
     * 初始化下蹲后跳跃模式
     */
    private void initDuckThenJump() {
        partSpacing = 70;
        parts = new ObstaclePart[] {
            new ObstaclePart(0, 40, 20, 25, false, true, 0),       // 低障碍物
            new ObstaclePart(partSpacing, -25, 20, 45, true, false, 0.4f)  // 高障碍物
        };
    }
    
    /**
     * 初始化双跳模式
     */
    private void initDoubleJump() {
        partSpacing = 45;
        parts = new ObstaclePart[] {
            new ObstaclePart(0, -20, 20, 40, true, false, 0),
            new ObstaclePart(partSpacing, -35, 20, 55, true, false, 0.3f),
            new ObstaclePart(partSpacing * 1.8f, -15, 20, 35, true, false, 0.6f)
        };
    }
    
    /**
     * 初始化时机关键模式
     */
    private void initTimingCritical() {
        partSpacing = 60;
        parts = new ObstaclePart[] {
            new ObstaclePart(0, 0, 20, 80, true, false, 0),        // 大障碍物
            new ObstaclePart(partSpacing, -10, 15, 20, true, false, 1.0f),  // 延迟激活
            new ObstaclePart(partSpacing * 1.5f, 50, 15, 20, false, true, 1.5f)
        };
    }
    
    /**
     * 初始化波浪模式
     */
    private void initWavePattern() {
        partSpacing = 35;
        parts = new ObstaclePart[] {
            new ObstaclePart(0, 20, 15, 30, false, true, 0),
            new ObstaclePart(partSpacing, -10, 15, 40, true, false, 0.2f),
            new ObstaclePart(partSpacing * 2, 25, 15, 25, false, true, 0.4f),
            new ObstaclePart(partSpacing * 3, -5, 15, 35, true, false, 0.6f)
        };
    }
    
    @Override
    public void update(float delta, int baseSpeed) {
        // 水平移动
        x += baseSpeed * delta;
        
        // 更新组合计时器
        comboTimer += delta;
        
        // 更新各部分的激活状态
        for (ObstaclePart part : parts) {
            part.isActive = comboTimer >= part.activationDelay;
        }
        
        // 检查是否需要重置
        if (x <= -width - getComboWidth()) {
            resetToRightSide();
        }
    }
    
    @Override
    public void render(Painter g) {
        if (isOnScreen(800)) {
            // 渲染组合提示
            renderComboHint(g);
            
            // 渲染各个部分
            for (int i = 0; i < parts.length; i++) {
                ObstaclePart part = parts[i];
                
                if (part.isActive) {
                    // 渲染激活的部分
                    renderActivePart(g, part, i);
                } else {
                    // 渲染未激活的部分（半透明预览）
                    renderInactivePart(g, part, i);
                }
            }
            
            // 渲染连接线
            renderConnectionLines(g);
        }
    }
    
    /**
     * 渲染组合提示
     */
    private void renderComboHint(Painter g) {
        // 在障碍物上方显示组合类型提示
        g.setColor(Color.argb(150, 255, 255, 0));
        String hint = getComboHint();
        g.drawString(hint, (int)(x + width/2 - hint.length() * 3), (int)(y - 30));
    }
    
    /**
     * 获取组合提示文字
     */
    private String getComboHint() {
        switch (comboType) {
            case JUMP_THEN_DUCK: return "跳+蹲";
            case DUCK_THEN_JUMP: return "蹲+跳";
            case DOUBLE_JUMP: return "双跳";
            case TIMING_CRITICAL: return "时机!";
            case WAVE_PATTERN: return "波浪";
            default: return "组合";
        }
    }
    
    /**
     * 渲染激活的部分
     */
    private void renderActivePart(Painter g, ObstaclePart part, int index) {
        int partX = (int)(x + part.relativeX);
        int partY = (int)(y + part.relativeY);
        
        // 使用不同颜色区分不同部分
        if (part.requiresJump) {
            g.setColor(Color.argb(180, 255, 100, 100)); // 红色 = 跳跃
        } else if (part.requiresDuck) {
            g.setColor(Color.argb(180, 100, 100, 255)); // 蓝色 = 下蹲
        } else {
            g.setColor(Color.argb(180, 100, 255, 100)); // 绿色 = 普通
        }
        
        g.fillRect(partX, partY, part.width, part.height);
        
        // 绘制边框
        g.setColor(Color.WHITE);
        g.drawRect(partX, partY, part.width, part.height);
        
        // 绘制操作图标
        renderActionIcon(g, part, partX, partY);
    }
    
    /**
     * 渲染未激活的部分
     */
    private void renderInactivePart(Painter g, ObstaclePart part, int index) {
        int partX = (int)(x + part.relativeX);
        int partY = (int)(y + part.relativeY);
        
        // 半透明预览
        g.setColor(Color.argb(80, 200, 200, 200));
        g.fillRect(partX, partY, part.width, part.height);
        
        // 虚线边框效果
        g.setColor(Color.argb(100, 255, 255, 255));
        if ((int)(comboTimer * 5) % 2 == 0) { // 闪烁效果
            g.drawRect(partX, partY, part.width, part.height);
        }
    }
    
    /**
     * 渲染操作图标
     */
    private void renderActionIcon(Painter g, ObstaclePart part, int partX, int partY) {
        int centerX = partX + part.width / 2;
        int centerY = partY + part.height / 2;
        
        g.setColor(Color.WHITE);
        
        if (part.requiresJump) {
            // 绘制向上箭头
            g.fillRect(centerX - 1, centerY - 5, 3, 8);
            g.fillRect(centerX - 3, centerY - 3, 7, 2);
        } else if (part.requiresDuck) {
            // 绘制向下箭头
            g.fillRect(centerX - 1, centerY - 3, 3, 8);
            g.fillRect(centerX - 3, centerY + 3, 7, 2);
        }
    }
    
    /**
     * 渲染连接线
     */
    private void renderConnectionLines(Painter g) {
        g.setColor(Color.argb(100, 255, 255, 0));
        
        for (int i = 0; i < parts.length - 1; i++) {
            ObstaclePart current = parts[i];
            ObstaclePart next = parts[i + 1];
            
            if (current.isActive && next.isActive) {
                int x1 = (int)(x + current.relativeX + current.width);
                int y1 = (int)(y + current.relativeY + current.height / 2);
                int x2 = (int)(x + next.relativeX);
                int y2 = (int)(y + next.relativeY + next.height / 2);
                
                g.drawLine(x1, y1, x2, y2);
            }
        }
    }
    
    @Override
    public void reset(float newX, float newY) {
        setPosition(newX, newY);
        comboTimer = 0;
        isPassed = false;
        isActive = true;
        
        // 重置所有部分
        for (ObstaclePart part : parts) {
            part.isActive = false;
        }
        
        // 随机重新选择组合类型
        ComboType[] types = ComboType.values();
        this.comboType = types[RandomNumberGenerator.getRandInt(types.length)];
        initializeCombo();
    }
    
    @Override
    public Rect getCollisionRect() {
        // 组合障碍物返回包含所有激活部分的大矩形
        if (parts == null || parts.length == 0) {
            collisionRect.set((int)x, (int)y, (int)x + width, (int)y + height);
            return collisionRect;
        }
        
        float minX = Float.MAX_VALUE, minY = Float.MAX_VALUE;
        float maxX = Float.MIN_VALUE, maxY = Float.MIN_VALUE;
        
        for (ObstaclePart part : parts) {
            if (part.isActive) {
                minX = Math.min(minX, x + part.relativeX);
                minY = Math.min(minY, y + part.relativeY);
                maxX = Math.max(maxX, x + part.relativeX + part.width);
                maxY = Math.max(maxY, y + part.relativeY + part.height);
            }
        }
        
        collisionRect.set((int)minX, (int)minY, (int)maxX, (int)maxY);
        return collisionRect;
    }
    
    /**
     * 获取特定部分的碰撞矩形
     */
    public Rect getPartCollisionRect(int partIndex) {
        if (partIndex < 0 || partIndex >= parts.length || !parts[partIndex].isActive) {
            return new Rect(); // 空矩形
        }
        return parts[partIndex].getCollisionRect(x, y);
    }
    
    @Override
    public boolean requiresJump() {
        // 检查当前是否有需要跳跃的激活部分
        for (ObstaclePart part : parts) {
            if (part.isActive && part.requiresJump) {
                return true;
            }
        }
        return false;
    }
    
    @Override
    public boolean requiresDuck() {
        // 检查当前是否有需要下蹲的激活部分
        for (ObstaclePart part : parts) {
            if (part.isActive && part.requiresDuck) {
                return true;
            }
        }
        return false;
    }
    
    @Override
    public int getDifficultyScore() {
        // 组合障碍物难度最高
        int baseScore = 5;
        
        switch (comboType) {
            case JUMP_THEN_DUCK: return baseScore + 2;
            case DUCK_THEN_JUMP: return baseScore + 2;
            case DOUBLE_JUMP: return baseScore + 3;
            case TIMING_CRITICAL: return baseScore + 4;
            case WAVE_PATTERN: return baseScore + 3;
            default: return baseScore;
        }
    }
    
    @Override
    public int getRewardScore() {
        return 50; // 组合障碍物奖励最高
    }
    
    /**
     * 获取组合宽度
     */
    private float getComboWidth() {
        if (parts == null || parts.length == 0) return width;
        
        float maxX = 0;
        for (ObstaclePart part : parts) {
            maxX = Math.max(maxX, part.relativeX + part.width);
        }
        return maxX;
    }
    
    /**
     * 重置到屏幕右侧
     */
    private void resetToRightSide() {
        x += 1200; // 组合障碍物需要更多空间
        y = RandomNumberGenerator.getRandIntBetween(250, 350);
        
        comboTimer = 0;
        isPassed = false;
        isActive = true;
        
        // 重置所有部分
        for (ObstaclePart part : parts) {
            part.isActive = false;
        }
    }
    
    /**
     * 获取组合类型
     */
    public ComboType getComboType() {
        return comboType;
    }
    
    /**
     * 获取激活部分数量
     */
    public int getActivePartCount() {
        int count = 0;
        for (ObstaclePart part : parts) {
            if (part.isActive) count++;
        }
        return count;
    }
    
    /**
     * 获取组合状态描述
     */
    public String getComboStatus() {
        return String.format("%s: %d/%d parts active, timer=%.1f", 
                comboType.name(), getActivePartCount(), parts.length, comboTimer);
    }
}